<?php

namespace app\common\model;

use app\common\library\AlipayFundService;
use app\common\library\WechatChapter;
use app\common\model\mycurrency\LeaseOrder;
use think\Exception;
use think\Model;
use think\Queue;
use traits\model\SoftDelete;

/**
 * 微信支付分订单模型
 */
class WechatChapterOrder Extends Model
{
    use SoftDelete;
    // 表名
    protected $name = 'wechat_chapter_order';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
    // 追加属性
    protected $append = [];

    //订单状态 商户已创建服务订单
    const STATE_CREATED='CREATED';
    //订单状态 服务订单进行中
    const STATE_DOING='DOING';
    //订单状态 服务订单完成
    const STATE_DONE='DONE';
    //订单状态 商户取消服务订单
    const STATE_REVOKED='REVOKED';
    //订单状态 服务订单已失效
    const STATE_EXPIRED='EXPIRED';

    const TERMINAL_WECHAT = 'wechat';//终端:wechat=微信
    const TERMINAL_ALIPAY = 'alipay';//终端:alipay=支付宝

    /**
     * 创建订单号
     * @return string
     */
    public static function createOutOrderNo()
    {
        $outOrderNo = date('YmdHis') . mt_rand(10000, 99999) . mt_rand(100, 999);
        $exists = self::where(['out_order_no' => $outOrderNo])->value('id');
        if ($exists) {
            return self::createOutOrderNo();
        }
        return $outOrderNo;
    }

    /**
     * 创建扣款单号
     * @return string
     */
    public static function createOuttradeNo()
    {
        $outOrderNo = date('YmdHis') . mt_rand(10000, 99999) . mt_rand(100, 999);
        $exists = self::where(['outtrade_no' => $outOrderNo])->value('id');
        if ($exists) {
            return self::createOuttradeNo();
        }
        return $outOrderNo;
    }



    /**
     * 生成免押订单并获取申请参数
     * @param int $lease_order_id 租赁订单id
     * @param int $user_id 用户id
     * @param static $description 说明
     * @param string $terminal 终端 wechat 微信（默认） ， alipay 支付宝
     * @param array $extend 扩展数据
     *
    */
    public static function generate($lease_order_id,$user_id,$description,$terminal = 'wechat',$extend = []){
        try {
            //生成免押订单
            $out_order_no = self::createOutOrderNo();
            $insert = [
                'user_id' => $user_id,
                'out_order_no' => $out_order_no,
                'state' => self::STATE_CREATED,
                'total_money' => 0,
                'createtime' => time(),
                'terminal' => $terminal,
            ];
            $insert = array_merge($insert,$extend);
            $chapter_order = self::create($insert);
            //获取免押申请参数
            if ($terminal == self::TERMINAL_WECHAT){//获取微信免押参数
                $wechatChapter = WechatChapter::getInstance();
                $maxPayAmount=config('wechatchapter.max_pay_amount');
                $checkData = $wechatChapter->createOrder($out_order_no, '', $description, $maxPayAmount);
            }elseif ($terminal == self::TERMINAL_ALIPAY){//获取支付宝免押参数
                $orderStr = AlipayFundService::createOrder(
                    '台球杆租赁芝麻免押授权',    // 订单标题
                    $out_order_no,                // 商户订单号
                    null,                       // 商户请求流水号（使用默认）
                    $description,
                    '台球杆租赁'                // 租赁项目名称
                );
                $checkData = [
                    'str' => $orderStr,
                    'out_order_no' => $out_order_no,
                ];
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
            return;
        }
        //添加定时任务
        $queue_default = config('queue.default');
        Queue::later(60, "app\common\job\ChapterOrder@operateTimeout", ['chapter_order_id' => $chapter_order->id], $queue_default);
        return [$chapter_order->id,$checkData];
    }

    /**
     * 免押授权成功回掉逻辑处理
     * @param string $outOrderNo 支付分订单号
    */
    public static function authorizeSuccess($outOrderNo){
        $wechatChapterOrderInfo = self::get(['out_order_no' => $outOrderNo]);
        if ($wechatChapterOrderInfo->state == self::STATE_CREATED) {//订单状态:CREATED=商户已创建服务订单
            //修改免押订单状态
            $wechatChapterOrderInfo->state = self::STATE_DOING;//订单状态:DOING=服务订单进行中
            $wechatChapterOrderInfo->save();

            //修改租赁订单状态
            trace(["1========================处理lease_order_id报错问题_authorizeSuccess 1==============================" => $wechatChapterOrderInfo],'error');

            LeaseOrder::where(['id' => $wechatChapterOrderInfo->lease_order_id])->update([
                'use_status' => LeaseOrder::USE_STATUS_JINXINGZHONG,
            ]);
            //发送开门指令 - 根据项目写具体逻辑
            //LeaseOrder::orderStartRenting($wechatChapterOrderInfo->lease_order_id);
            //查询隔扣内杆子的卡id
            trace(["2========================处理lease_order_id报错问题_authorizeSuccess 3==============================" => $wechatChapterOrderInfo],'error');
            LeaseOrder::orderBlockIdQuery($wechatChapterOrderInfo->lease_order_id);
        }elseif ($wechatChapterOrderInfo->state == self::STATE_EXPIRED){//订单状态:EXPIRED=服务订单已失效 【下单后如果用户长时间没有通过免押 订单会失效】
            //取消免押
            trace(["3========================处理lease_order_id报错问题_authorizeSuccess 2==============================" => $wechatChapterOrderInfo],'error');
            $lease_order = LeaseOrder::where(['id' => $wechatChapterOrderInfo->lease_order_id])->find();
            if($lease_order && $lease_order->use_status == LeaseOrder::USE_STATUS_YIQUXIAO){//租赁订单存在 并且 租赁订单已取消
                //执行取消免押操作
                hook('handelWechatPayScoreCancel', ['order_id' => $wechatChapterOrderInfo['id']]);
            }
        }
    }

}
